package com.lushuan.ch11_springboot_test.demo.threadpool;

/**
 * ch5_Java中sleep和wait方法的区别
 */
class SharedResource {
    public synchronized void waitingMethod() {
        try {
            System.out.println(Thread.currentThread().getName() + " is waiting.");
            wait(); // 释放锁并等待通知
            System.out.println(Thread.currentThread().getName() + " resumed.");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("Thread was interrupted.");
        }
    }

    public synchronized void notifyingMethod() {
        System.out.println(Thread.currentThread().getName() + " is notifying.");
        notify(); // 唤醒等待的线程
    }
}

public class WaitNotifyExample {

    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        Thread t1 = new Thread(() -> resource.waitingMethod(), "Thread-1");
        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(1000); // 确保 t1 先执行
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            resource.notifyingMethod();
        }, "Thread-2");

        t1.start();
        t2.start();
    }

}

